<?php

namespace App\Http\Controllers\Api;

use App\Blocks\User;
use App\Http\Controllers\Controller;
use App\Libs\Message;
use App\Models\ActivityAddress;
use App\Models\ActivityAnswer;
use App\Models\ActivityUser;
use function GuzzleHttp\Psr7\build_query;
use Illuminate\Http\Request;

class ActivityUserController extends Controller
{
    private $dx_api_url = 'http://wx.gx.189.cn/i/bind/wx/third/index';
    private $dx_appid = 'jlwl';
    private $dx_key = 'jlwl_20180919';

    public function getActivityUserInfo(){
        global $g_uid;
        $userBlock = new User();

        $userInfo = $userBlock->getActivityUserInfoByUid($g_uid);

        $userInfo->xiaohongbao = (int)(($userInfo->popularity / 6) + (int)($userInfo->tacit / 10));
        $userInfo->dahongbao = (int)($userInfo->tacit / 20);
        $userInfo->popularity = (int)($userInfo->popularity/6);
        $userInfo->total_popularity = (int)($userInfo->total_popularity/6);
        $userInfo->used_popularity = (int)($userInfo->used_popularity/6);

        $answer = $userBlock->answerList($g_uid);

        $invite = $userBlock->inviteList($g_uid);

        $prize = $userBlock->prizeLogList($g_uid);

        $rank = $userBlock->rankList();

        return response()->json(Message::setResponseInfo('SUCCESS', [
            'user' => $userInfo,
            'answer' => $answer,
            'rank' => $rank,
            'invite' => $invite,
            'prize' => $prize
        ]));
    }

    public function getUserInfo($uid){
        $userBlock = new User();
        $userInfo = $userBlock->getActivityUserInfoByUid($uid);
        return response()->json(Message::setResponseInfo('SUCCESS', $userInfo));
    }

    public function answer(Request $request){
        global $g_uid;
        $answer = ActivityAnswer::where('ask_uid', $g_uid)
            ->orderBy('create_time', 'desc')
            ->get();
        return response()->json(Message::setResponseInfo('SUCCESS', $answer));
    }

    public function myInvite(Request $request){
        global $g_uid;
        $invite = ActivityUser::where('invite_uid', $g_uid)
            ->orderBy('create_time', 'desc')
            ->get();
        return response()->json(Message::setResponseInfo('SUCCESS', $invite));
    }

    public function rank(){
        $rank = ActivityUser::orderBy('total_tacit', 'desc')
            ->take(100)
            ->get();
        return response()->json(Message::setResponseInfo('SUCCESS', $rank));
    }

    public function bindMobile(Request $request){
        $validation = \Validator::make($request->all() , [
            'mobile'                    => 'required',
            'code'                      => 'required',
        ] , [
            'mobile.required'               => '请填写手机号',
            'code.required'               => '请填写验证码',
        ]);
        if($validation->fails()){
            $error = $validation->errors()->all();
            return response()->json(Message::setResponseInfo('FAILED', '', '402', $error[0]));
        }

        global $g_uid;
        $mobile = $request->get('mobile');
        $code = $request->get('code');

        $checkCode = \Cache::get($mobile);
        if($code !== $checkCode){
            return response()->json(Message::setResponseInfo('VERTIFY_CODE_ERROR'));
        }

        $userBlock = new User();
        $user = $userBlock->getActivityUserInfoByUid($g_uid);

        $params = [
            'method' => 'doBind',
            'appid' => $this->dx_appid,
            'timestamp' => date('YmdHis', time()),
            'openid' => $user->openid,
            'mobile' => $mobile
        ];

        ksort($params);

        $signTmp = build_query($params)."&key={$this->dx_key}";
        $sign = strtoupper(md5($signTmp));
        $sign =strtoupper(hash_hmac('sha256', $sign, $this->dx_key));
        $params['sign'] = $sign;

        try {
            $data = curlGet($this->dx_api_url . '?' . build_query($params));
            \Log::debug($data);
            $data = json_decode($data);

            if ($data->result == '0') {
                if(ActivityUser::where('id', $g_uid)->update(['mobile' => $mobile]) === false){
                    return response()->json(Message::setResponseInfo('FAILED'));
                }else{
                    return response()->json(Message::setResponseInfo('SUCCESS'));
                }
            } else {
                return response()->json(Message::setResponseInfo('', '', '842', $data->msg));
            }
        }catch (\Exception $exception){
            \Log::error($exception);
            return response()->json(Message::setResponseInfo('FAILED'));
        }


    }

    public function isBindMobile(){
        global $g_uid;
        $userBlock = new User();
        $user = $userBlock->getActivityUserInfoByUid($g_uid);
        $params = [
            'method' => 'doCheckBind',
            'appid' => $this->dx_appid,
            'timestamp' => date('YmdHis', time()),
            'openid' => $user->openid
        ];

        ksort($params);

        $signTmp = build_query($params)."&key={$this->dx_key}";
        $sign = strtoupper(md5($signTmp));
        $sign =strtoupper(hash_hmac('sha256', $sign, $this->dx_key));
        $params['sign'] = $sign;

        try {
            $data = curlGet($this->dx_api_url . '?' . build_query($params));

            \Log::debug($data);
            $data = json_decode($data);

            if ($data->result == '0') {
                $mobile = $data->mobile;
                $mobile = openssl_decrypt(hex2bin($mobile),'DES-ECB',$this->dx_key, OPENSSL_NO_PADDING);
                $pad = (ord($mobile{strlen($mobile) - 1}));
                $mobile = substr($mobile, 0, -1 * $pad);
                if(empty($mobile)){
                    return response()->json(Message::setResponseInfo('', '', '842', $data->msg));
                }

                ActivityUser::where('id', $g_uid)->update([
                    'mobile' => $mobile
                ]);
                return response()->json(Message::setResponseInfo('SUCCESS'));
            } else {
                return response()->json(Message::setResponseInfo('', '', '842', $data->msg));
            }
        }catch (\Exception $exception){
            \Log::error($exception);
            return response()->json(Message::setResponseInfo('FAILED'));
        }
    }

    public function address(Request $request){
        global $g_uid;
        $validation = \Validator::make($request->all() , [
            'mobile'                    => 'required',
            'address'                   => 'required',
            'name'                      => 'required',
        ] , [
            'mobile.required'               => '请填写手机号',
            'address.required'              => '请填写收货地址',
            'name.required'                 => '请填写收货人名称',
        ]);
        if($validation->fails()){
            $error = $validation->errors()->all();
            return response()->json(Message::setResponseInfo('FAILED', '', '402', $error[0]));
        }

        if(ActivityAddress::updateOrCreate(['uid' => $g_uid], [
            'name' => $request->get('name'),
            'address' => $request->get('address'),
            'mobile' => $request->get('mobile'),
            'create_time' => date('Y-m-d H:i:s', time())
        ])){
            return response()->json(Message::setResponseInfo('SUCCESS'));
        }else{
            return response()->json(Message::setResponseInfo('FAILED'));
        }
    }


    public function cyCount(){
        $count = \Cache::get('cy:count');
        if(empty($count)){
            $count = ActivityUser::whereNotNull('answer_goods_id')->count();
        }
        return response()->json(Message::setResponseInfo('SUCCESS', $count + 18888));
    }
}
